import { useRef, useEffect } from 'react'

const GrafanaWrap = (props) => {
  const iframe = useRef(null);

  const onUrlChange = props.onUrlChange;
  const urlChangeInvokeInterval = props.urlChangeInvokeInterval || 1000;

  let curUrl = props.src;

  useEffect(() => {
    iframe.current.contentWindow.addEventListener('DOMContentLoaded', ev => {
      const new_style_element = document.createElement("style");
      new_style_element.textContent = "nav[data-testid='sidemenu'] { visibility: hidden; width:0 }"
      iframe.current.contentDocument.head.appendChild(new_style_element);
    }
    );

    iframe.current.contentWindow.onbeforeunload = null;
    // iframe.current.contentWindow.addEventListener("beforeunload", handleBeforeUnload, {
    //   once: false
    // })

    if (!!onUrlChange) {
      setInterval(() => {
        if (!!iframe.current && !!iframe.current.contentWindow) {
          let newUrl = iframe.current.contentWindow.location.href;
          if (!!newUrl && newUrl !== curUrl) {
            curUrl = newUrl;
            onUrlChange(newUrl);
          }
        }
      }, urlChangeInvokeInterval);
    }
  }, []);



  return (
    <iframe
      src={props.src}
      width="100%"
      frameBorder="0"
      ref={iframe}
      onLoad={res => {
        const new_style_element = document.createElement("style");
        new_style_element.textContent = "nav[data-testid='sidemenu'] { visibility: hidden; width:0 }"
        iframe.current.contentDocument.head.appendChild(new_style_element);
      }}
      style={{ height: "calc(100vh - 80px)" }}
    />
  )
}

export default GrafanaWrap;